package com.atguigu.bigdata.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.edu.realtime.app.BaseAppV1;
import com.atguigu.bigdata.edu.realtime.bean.ExamQuestionBean;
import com.atguigu.bigdata.edu.realtime.common.Constant;
import com.atguigu.bigdata.edu.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.edu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.math.BigDecimal;

public class Dws_14_DwsExamQuestionCountWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_14_DwsExamQuestionCountWindow().init(
                4014,
                2,
                "Dws_14_DwsExamQuestionCountWindow",
                Constant.DWD_EXAM_QUESTION_DETAIL
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1.将数据转换成POJO
        SingleOutputStreamOperator<ExamQuestionBean> beanStream = parseToObj(stream);
        // 2.将数据写入ClickHouse
        writeToClickhouse(beanStream);
    }

    private void writeToClickhouse(SingleOutputStreamOperator<ExamQuestionBean> beanStream) {
        beanStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_exam_question_count_window", ExamQuestionBean.class));
    }

    private SingleOutputStreamOperator<ExamQuestionBean> parseToObj(DataStreamSource<String> stream) {
        return stream
                .map(new RichMapFunction<String, ExamQuestionBean>() {
            @Override
            public ExamQuestionBean map(String s) throws Exception {
                JSONObject obj = JSON.parseObject(s);
                String questionId = obj.getString("question_id");
                Long ansCount = 0L;
                Long ansRightCount = 0L;
                Long UvCt = 0L;
                Long arUvCt = 0L;
                BigDecimal arRate = new BigDecimal(0);
                return new ExamQuestionBean("", "", questionId, ansCount, ansRightCount, UvCt, arUvCt,arRate, AtguiguUtil.dateToTs(obj.getString("submit_time")));
            }
        });
    }
}
